package com.pig4cloud.pig.module.service.promoter.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.TransactionalException;
import com.pig4cloud.pig.common.core.util.OrderUtil;
import com.pig4cloud.pig.common.core.wx.WxAppPay;
import com.pig4cloud.pig.module.api.entity.promoter.PromoterSettlement;
import com.pig4cloud.pig.module.api.entity.promoter.PromoterUserRecord;
import com.pig4cloud.pig.module.api.entity.wx.WxPayTransaction;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.mapper.promoter.PromoterSettlementMapper;
import com.pig4cloud.pig.module.mapper.promoter.PromoterUserRecordMapper;
import com.pig4cloud.pig.module.service.promoter.IPromoterSettlementService;
import com.pig4cloud.pig.module.service.promoter.IPromoterUserRecordService;
import com.pig4cloud.pig.module.service.wx.IWxPayTransactionService;
import com.pig4cloud.pig.module.service.wx.IWxTemplateService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 推广员 结算单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-11-11
 */
@Service
public class PromoterSettlementServiceImpl extends ServiceImpl<PromoterSettlementMapper, PromoterSettlement> implements IPromoterSettlementService {

	@Resource
	private PromoterSettlementMapper promoterSettlementMapper;
	@Resource
	private PromoterUserRecordMapper promoterUserRecordMapper;
	@Resource
	private IPromoterUserRecordService promoterUserRecordService;
	@Resource
	private IWxUserService wxUserService;
	@Resource
	private IWxPayTransactionService payTransactionService;
	@Resource
	private IWxTemplateService wxTemplateService;

	@Value("${web.appid}")
	private String appid;
	@Value("${web.appidMp}")
	private String appidMp;
	@Value("${web.secret}")
	private String secret;
	@Value("${web.mch_id}")
	private String mch_id;
	@Value("${web.api_key}")
	private String api_key;
	@Value("${web.keyPath}")
	private String keyPath;//微信支付的回调地址

	@Override
	@Transactional
	public Map<String, Object> checkRecord(PromoterSettlement promoterSettlement) {

		Map<String,Object> map = new HashMap<>();
		int ret = 0;
		try{
			int status = 0;
			if(promoterSettlement.getState() == 1){
				promoterSettlement.setState(2);
				String tradeNo = OrderUtil.getPayNo();
				promoterSettlement.setTradeNo(tradeNo);
				map.put("result_code","FAIL");
				map.put("err_code_des","请求失败");
				WxAppPay wxAppPay = new WxAppPay("", secret, appid, mch_id,api_key);
				Map<String, String> retRequest = wxAppPay.weixinChangePay(promoterSettlement.getTradeNo(),promoterSettlement.getPayMoney(),promoterSettlement.getPromoterWxOpenId(),keyPath,"领蛋结算款");
				if(retRequest.containsKey("return_code")){
					String return_code = retRequest.get("return_code");
					String result_code = retRequest.get("result_code");
					String err_code_des = retRequest.containsKey("err_code_des") ? retRequest.get("err_code_des") : "";
					map.put("result_code",result_code);
					map.put("err_code_des",err_code_des);
					promoterSettlement.setResultCode(result_code);
					if(result_code.equals("SUCCESS")) {
						promoterSettlement.setPayState(1);//支付成功
						promoterSettlement.setPayTime(new Date());
						map.put("err_code_des","提现成功");
						//结算状态 0  - 待结算  1 - 已结算  2 - 取消结算 3 - 已打款  4 - 打款失败
						promoterSettlement.setState(3);

						WxUser wxUser = wxUserService.findById(promoterSettlement.getPromoterWxUserId());
						// 添加 微信支付的 动账记录
						WxPayTransaction transaction = new WxPayTransaction();
						transaction.setTransactionNo(promoterSettlement.getTradeNo());
						transaction.setPayType(0);// 0 -微信支付
						transaction.setTransactionId(promoterSettlement.getTradeNo());
						transaction.setUserId(wxUser.getId());
						transaction.setFeeType("promoter_settle");
						transaction.setTotalMoney(promoterSettlement.getPayMoney());
						if(StrUtil.isNotEmpty(wxUser.getNickName())){
							transaction.setNickName(EmojiParser.parseToAliases(wxUser.getNickName()));
						}
						transaction.setCreateTime(new Date());
						transaction.setInOrOut(0);//动账  0 - 出账 1 - 进账
						transaction.setRemark("推广结算款");
						payTransactionService.save(transaction);

						status = 1;
					}else{
						promoterSettlement.setState(4);
						promoterSettlement.setPayState(2);//支付失败
						promoterSettlement.setErrCodeDes(err_code_des);
					}
					String pay_str = retRequest.get("pay_str");
					String reback_str = retRequest.get("reback_str");
					promoterSettlement.setPayStr(pay_str);
					promoterSettlement.setRebackStr(reback_str);
				}
			}

			ret = promoterSettlementMapper.updateById(promoterSettlement);
			if(ret <= 0){
				throw new TransactionalException("cashRecordMapper updateById error");
			}
			//批量修改 邀请记录的状态
			promoterUserRecordService.update(new LambdaUpdateWrapper<PromoterUserRecord>()
				.set(PromoterUserRecord::getState,2)
				.set(PromoterUserRecord::getPaySettleTime, new Date())
				.eq(PromoterUserRecord::getSettleId,promoterSettlement.getId()));

			if(status == 1){
				WxUser wxUser = wxUserService.findById(promoterSettlement.getPromoterWxUserId());
				wxTemplateService.sendWxMsgPromoterSettle(wxUser,promoterSettlement,promoterSettlement.getPayMoney().doubleValue());
			}
			map.put("ret",ret);
			return map;
		}catch (Exception e){
			e.printStackTrace();
			throw new TransactionalException("splitAccountRecordMapper insert error");
		}
	}
}
